/**
 * File: ParallelSingleSubmitController.java
 * Created by: mhaimel
 * Created on: 14 Jul 2009
 * CVS:  $Id: ParallelSingleSubmitController.java,v 1.1 2009/08/05 15:16:11 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller;

import java.io.Serializable;
import java.util.List;

import javolution.util.FastList;

import org.apache.commons.lang.NotImplementedException;

import uk.ac.ebi.curtain.management.IProcessor;
import uk.ac.ebi.curtain.management.InterceptorInfo;

/**
 * @author mhaimel
 *
 */
public abstract class ParallelSingleSubmitController<I extends Serializable, O extends Serializable, P extends IProcessor<I, O>> extends ParallelController<I, O, P> {
	private Boolean HAS_SUBMITTED = false;
	private static final Object _LOCK_OBJECT = new Object();
	private List<I> inList = new FastList<I>();
	
	@Override
	public synchronized void handle(I input, InterceptorInfo info) {
		getInputList().add(input);
	}
	
	@Override
	protected P buildJob(I input, InterceptorInfo info) {
		throw new NotImplementedException("This method should not be calls as it is overwritten and not in use!!!");
	}
	
	@Override
	public void shutDown(boolean force, InterceptorInfo info) {
		if(!force){
			syncSingleSubmit(getInputList());
		}
		super.shutDown(force, info);
	}

	private synchronized void syncSingleSubmit(List<I> inputList){
		synchronized (_LOCK_OBJECT) {			
			if(!HAS_SUBMITTED){
				getLog().debug("Single submit of jobs " + getQueueName() + " ...");
				singleSubmit(inputList);
				HAS_SUBMITTED = true;
			}
		}
	}
	
	protected abstract void singleSubmit(List<I> inputList);

	protected void setInputList(List<I> inList) {
		this.inList = inList;
	}

	protected List<I> getInputList() {
		return inList;
	}


}
